package by.grsu.pereverzev.page;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.ListChoice;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.PropertyModel;

import by.grsu.pereverzev.app.PereverzevWebApplication;
import by.grsu.pereverzev.dao.impl.ApplicationDao;
import by.grsu.pereverzev.dao.impl.BillDao;
import by.grsu.pereverzev.dao.impl.PassengerDao;
import by.grsu.pereverzev.entity.Application;
import by.grsu.pereverzev.entity.Bill;
import by.grsu.pereverzev.entity.Passenger;
import by.grsu.pereverzev.entity.Flight;

public class FlightOrderPage extends WebPage {

	private static final SimpleDateFormat sdf = new SimpleDateFormat("DD.mm.yyyy HH:MM");
	private Long selectedPassengerId = new Long(0);
	
	public FlightOrderPage(final Flight flight) {
		super();
				

		final Form<Flight> form = new Form<Flight>("form");
		add(form);
		
        form.add(new ListChoice<Long>("passengerSelection", new PropertyModel<Long>(this, "selectedPassengerId"), getPassengersIds()));

		form.add(new Label("id", flight.getId()));
		form.add(new Label("destStation", flight.getDestStation()));
		form.add(new Label("dateOfDeparture", sdf.format(flight.getDateOfDeparture())));
		form.add(new Label("cost", flight.getCost()));
        

		form.add(new SubmitLink("order") {
			@Override
			public void onSubmit() {
				super.onSubmit();
				System.out.println("let's order! flight="+flight+" passengerId="+selectedPassengerId);
			 	Bill bill = new Bill(flight.getCost(), selectedPassengerId);			 	
				BillDao billDao = new BillDao(PereverzevWebApplication.DATA_XML_FOLDER);
				System.out.println("save bill="+bill);
				Long billId = billDao.saveNew(bill);
				Application appl = new Application(selectedPassengerId, flight.getId(), billId);
				ApplicationDao applDao = new ApplicationDao(PereverzevWebApplication.DATA_XML_FOLDER);
				System.out.println("save application="+appl);
				applDao.saveNew(appl);
				
				setResponsePage(new PassengersListPage());
			}
		});
		
		form.add(new Link("cancel") {
			@Override
			public void onClick() {
				setResponsePage(new FlightListPage());
			}
		});
	}
	
	private List<Long> getPassengersIds() {
		PassengerDao passengerDao = new PassengerDao(PereverzevWebApplication.DATA_XML_FOLDER);
		List<Passenger> passengers = passengerDao.getAll();
		List<Long> ids = new ArrayList<Long>(passengers.size());
		for (Passenger p : passengers) 
			ids.add(p.getId());
		return ids;
	}
}
